import { getUserDetailById, getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  updateToken(state, token) {
    state.token = token

    // 存储到本地 Cookie
    setToken(token)
  },
  updateUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // user login
  async userLogin({ commit }, userInfo) {
    const res = await login(userInfo)
    commit('updateToken', res.data)
    return res
  },
  async getUserProfile({ commit }) {
    const res1 = await getUserInfo()
    const res2 = await getUserDetailById(res1.data.userId)
    // console.log(res1)
    // console.log(res2)
    commit('updateUserInfo', { ...res1.data, ...res2.data })
    return { ...res1.data, ...res2.data }
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

